<?php

namespace App\Service;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use GuzzleHttp\Client;
use SebastianBergmann\CodeCoverage\Report\PHP;
use function Symfony\Component\String\s;
use Hyperf\DbConnection\Db;
//use Hyperf\Di\Annotation\Inject;

#微信公众接口
class CommService
{
//    #[Inject]
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
        $this->httpclient = new Client();

    }
    #query_order 查询创建的订单（现金单，非代币单）
    public function query_orders($applet_id,$xc_open_id,$order_id=0) {

        $payUrl = "/xpay/query_order";
        $postData = [
            'openid' => $xc_open_id,
            'env'=>0,
            'order_id' =>$order_id,
        ];
        $access_token = $this->get_wx_access_token($applet_id);

        $pay_sig = $this->get_paySig($applet_id,$payUrl,$postData);
        $url = "https://api.weixin.qq.com/xpay/query_order?access_token=$access_token&pay_sig=$pay_sig";
        $res = $this->curl_post($url,$postData);
        if($res['errcode'] == 0) {
            return $res['order'];
        } else {
            return false;
        }
    }
    #present_currency 代币赠送接口，由于目前不支付按单号查赠送单的功能，所以当需要赠送的时候可以一直重试到返回0或者返回268490004（重复操作）为止
    public function present_currency($applet_id,$xc_open_id,$order_id,$amount,$type=1) {
        $payUrl = "/xpay/present_currency";
        $postData = [
            'openid' => $xc_open_id,
            'env'=>0,
            'order_id' =>$order_id,#order_id	string	赠送单号
            'amount'=>$amount,# amount	int	赠送金额
            'device_type' =>$type,#device_type	int	1-安卓 2-苹果
        ];
        var_dump($postData);
        var_dump('-----------------');
        $access_token = $this->get_wx_access_token($applet_id);
        $pay_sig = $this->get_paySig($applet_id,$payUrl,$postData);
        $url = "https://api.weixin.qq.com/xpay/present_currency?access_token=$access_token&pay_sig=$pay_sig";
        $res = $this->curl_post($url,$postData);

        var_dump($res);
        if($res['errcode'] == 0) {
            return $res;
        } else {
            return false;
        }
    }
    #currency_pay扣减代币（一般用于代币支付）
    public function currency_pay($applet_id,$user_info,$amount,$order_id) {

        $open_id = $user_info->xc_open_id;
        $user_ip = $user_info->ip;
        $login_info = $this->redisService->hGet('login_info:'.$applet_id,$open_id);
        $login_info = json_decode($login_info,true);
        $session_key = $login_info['session_key'];
        $payUrl = "/xpay/currency_pay";

        $postData = [
            'openid' => $open_id,
            'env'=>0,
            'user_ip'=>$user_ip,
            'amount'=>$amount,#支付的代币数量
            'order_id'=>$order_id,#订单号
            'payitem'=>[],#物品信息。记录到账户流水中。如:[{"productid":"物品id", "unit_price": 单价, "quantity": 数量}]
            'remark'=>'购买剧集',#备注
            'device_type'=>1,#平台类型1-安卓 2-苹果
        ];
        var_dump($postData);
        $access_token = $this->get_wx_access_token($applet_id);
        $pay_sig = $this->get_paySig($applet_id,$payUrl,$postData);
        $signature = $this->get_signature($postData,$session_key);

        $url = "https://api.weixin.qq.com/xpay/currency_pay?access_token=$access_token&pay_sig=$pay_sig&signature=$signature";
        $res = $this->curl_post($url,$postData);
        var_dump($res);
        if($res['errcode'] == 0) {
            return $res;
        } else {
            var_dump($res);
            return false;
        }
    }

    #微信查询余额
    public function query_user_balance($applet_id,$user_info) {
        $open_id = $user_info['xc_open_id'];
        $user_ip = $user_info['ip'];
        $payUrl = "/xpay/query_user_balance";
        $postData = [
            'openid' => $open_id,
            'env'=>0,
            'user_ip' =>$user_ip
        ];
        $access_token = $this->get_wx_access_token($applet_id);
        $pay_sig = $this->get_paySig($applet_id,$payUrl,$postData);
        $url = "https://api.weixin.qq.com/xpay/query_user_balance?access_token=$access_token&pay_sig=$pay_sig";
        $res = $this->curl_post($url,$postData);
        var_dump('查询余额');
        var_dump($res);
        if($res['errcode'] == 0) {
            return $res;
        } else {
            return false;
        }
    }
    #支付签名
    public function get_paySig($applet_id,$url,$signData) {
//        $redis_key = "applet:config";
//        $applet_info = $this->redisService->hGet($redis_key,$applet_id);
//        $applet_info = json_decode($applet_info,true);
        $applet_info = [];
        if (empty($applet_info)) {
            # 获取小程序基本信息
            $applet_infos = Db::table("applet")->where([
                "id" => $applet_id
            ])->first();
            $applet_info['AppKey'] = $applet_infos->AppKey;
        }
        $appkey = $applet_info['AppKey'];
//        $appkey = getenv('appkey'.$applet_id);
//        var_dump($appkey);
        $paySig = $this->calcPaySig($url, $signData, $appkey);
        return $paySig;
    }
    #用户态签名
    public function get_signature($postBody,$sessionKey="") {

        $signature = $this->calcSignature($postBody, $sessionKey);
        return $signature;
    }
    private function calcSignature($postBody, $sessionKey)
    {
        $needSignMsg = json_encode($postBody,);

        $signature = hash_hmac('sha256', $needSignMsg, $sessionKey);
        return $signature;
    }
    private function calcPaySig($uri, $postBody, $appkey)
    {
        $needSignMsg = $uri . '&' . json_encode($postBody);
        $paySig = hash_hmac('sha256', $needSignMsg, $appkey);
        return $paySig;
    }


    public function curl_get($url){
        echo "到这历来了".PHP_EOL;
        #/usr/bin/openssl
        #yes --with-openssl-dir=/usr/local/opt/openss
        $response = $this->httpclient->request('GET', $url);
        $content = $response->getBody()->getContents();
        return json_decode($content,true);
    }
    public function curl_post($url,$data){
        $headers = [
            'Content-Type' => 'application/json',
        ];
        $response = $this->httpclient->post($url, [
            'headers' => $headers,
            'json' => $data,
        ]);
        $content = $response->getBody()->getContents();
        return json_decode($content,true);
    }

    # 获取wx_access_token
    public function get_wx_access_token(string $applet_id="10000"){
        $key = 'wx_access_token';
        $key .= $applet_id;
        $access_token = $this->redisService->get($key);
        if(empty($access_token)){
            $wx_appid = '';
            $wx_secret = '';
            # 获取小程序基本信息
            $applet_info = Db::table("applet")->where([
                "id"=>$applet_id
            ])->first();

            if(!empty($applet_info)){
                $wx_appid = $applet_info->app_id;
                $wx_secret = $applet_info->app_secret;
            }
            $access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wx_appid}&secret={$wx_secret}";
            $access_token_info = self::curl_get($access_token_url);
            if (!empty($access_token_info["access_token"])){
                $access_token = $access_token_info["access_token"];
                $this->redisService->Set($key,$access_token);
                $this->redisService->expire($key,7100);
            }else{
                $access_token = "";
            }
        }
        return $access_token;
    }

    public function getPhoneNumber($code){
        $access_token = self::get_wx_access_token();
        $phone_url ="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$access_token;
//        $response = $this->httpclient->post($phone_url,"form_params"=[
//            'code' => $jscode
//        ]);
        $response = $this->httpclient->request('POST', $phone_url,[
            "json"=>['code'=>$code]
        ]);
        $content = $response->getBody()->getContents();
        return json_decode($content,true);
    }



    public function buld_openid_phone($data){
        $this->redisService->hSet("wx_openid_phone",$data["openid"],$data["phoneNumber"]);
    }

    public function get_user_home_popup_goods(int $user_id){
        $user_id = (string)$user_id;
        #首页弹出商品频率
        $redis_key = "jingy:user:home_popup:".date("Ymd");
        $number = $this->redisService->hGet($redis_key,$user_id);
        $number = (int)$number;
        $s_number = $number + 1;
        $this->redisService->hSet($redis_key,$user_id,$s_number);
        $this->redisService->expire($redis_key,86400);
        if ($s_number>7){
            return 0;
        }else{
            return $s_number;
        }
    }

    public function object_to_array($obj){
        # 对象列表装好为空
        $new_array = [];
        if ($obj){
            foreach ($obj as $key=>$value){
                $new_array[$key] = (array)$value;
            }
        }
        return $new_array;
    }
    #notify_provice_goods 通知已经发货完成（只能通知现金单）,正常通过xpay_goods_deliver_notify消息推送返回成功就不需要调用这个api接口。这个接口用于异常情况推送不成功时手动将单改成已发货状态
//    public function notify_provice_goods($applet_id,$xc_open_id) {
//
//    }
//    #download_bill 用于下载小程序账单，第一次调用触发生成下载url，可以间隔轮训来获取最终生成的下载url。
//    public function download_bill($applet_id,$xc_open_id) {
//
//    }
//    #refund_order 对使用jsapi接口下的单进行退款，此接口只是启动退款任务成功，启动后需要调用query_order接口来查询退款单状态，等状态变成退款完成后即为最终成功
//    public function refund_order($applet_id,$xc_open_id) {
//
//    }

//    #query_biz_balance 查询商家账户里的可提现余额
//    public function query_biz_balance($applet_id,$xc_open_id) {
//
//    }
//    #create_withdraw_order 创建提现单
//    public function create_withdraw_order($applet_id,$xc_open_id) {
//
//    }
//    #query_withdraw_order 查询提现单
//    public function query_withdraw_order($applet_id,$xc_open_id) {
//
//    }
}